package com.genius.utils;

import cn.hutool.core.util.RandomUtil;
import com.genius.enums.ResponseType;
import com.genius.exception.GraceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

import static com.genius.constant.CodeConstants.EMAIL_CHECK_ID;

@Component
public class CheckUtils {

    @Autowired
    private RedisUtils redisUtils;

    /**
     * 获取邮箱验证码
     * @param email 邮箱
     * @return 邮箱验证码
     */
    public String getEmailVerificationCode(String email){
        String emailCheckId = getEmailCheckId(email);
        Boolean hasKey = redisUtils.hasKey(emailCheckId);
        //判断key是否存在
        if (hasKey) {
            GraceException.display(ResponseType.VERIFICATION_CODE_SEND_ERROR);
        }
        String emailCheckCode = RandomUtil.randomNumbers(6);
        // 缓存验证码
        redisUtils.setCacheObject(emailCheckId, emailCheckCode, 60, TimeUnit.SECONDS);
        return emailCheckCode;
    }

    /**
     * 验证邮箱验证码是否匹配
     * @param checkEmail 待验证邮箱
     * @param checkCode 待验证码
     */
    public void checkEmailVerificationCode(String checkEmail, String checkCode){
        //校验验证码
        String email = getEmailCheckId(checkEmail);
        Boolean hasKey = redisUtils.hasKey(email);
        //判断key是否存在，不存在返回失效
        if (hasKey == null || !hasKey) {
            GraceException.display(ResponseType.VERIFICATION_CODE_INVALID_ERROR);
        }
        //验证邮箱验证码
        String emailCheckCode = redisUtils.getCacheObject(email);
        if(!emailCheckCode.equals(checkCode)){
            GraceException.display(ResponseType.VERIFICATION_CODE_NOT_MATCH_ERROR);
        }
    }

    /**
     * 添加redis key前缀
     * @param email 邮箱
     * @return redis key
     */
    private String getEmailCheckId(String email) {
        return EMAIL_CHECK_ID + email;
    }
}
